package com.tim.test.download;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.epub.EpubReader;
import nl.siegmann.epublib.service.MediatypeService;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class EpubToTxt {

    public static void convertEpubToTxt(String epubFilePath, String outputTxtPath) {
        try (InputStream epubStream = new FileInputStream(epubFilePath)) {
            // 读取 EPUB 文件
            EpubReader epubReader = new EpubReader();
            Book book = epubReader.readEpub(epubStream);

            // 准备输出文件
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(outputTxtPath), "UTF-8"))) {

                // 遍历所有内容资源
                book.getContents().forEach(spineItem -> {
                    if (MediatypeService.XHTML.equals(spineItem.getMediaType())) {
                        try {
                            String content = new String(spineItem.getData(), "UTF-8");
                            // 简单提取文本内容（去除 HTML 标签）
                            String textOnly = content.replaceAll("<[^>]*>", "").trim();
                            writer.write(textOnly);
                            writer.newLine();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            System.out.println("转换完成，文件保存在: " + outputTxtPath);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String epubFile = "D:\\aa\\潜规则.epub";   // 替换为你的 EPUB 文件路径
        String txtFile = epubFile+".txt";  // 替换为你想保存的 TXT 文件路径

        convertEpubToTxt(epubFile, txtFile);
    }
}

